package com.frxuexi.myroom.view

import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material3.Button
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil3.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.BaseTitle
import com.frxuexi.lib_base.UiState
import com.frxuexi.lib_base.room.Leave
import com.frxuexi.myroom.intent.LeaveIntent
import com.frxuexi.myroom.viewmodel.LeaveViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch

/**
 * 申请请假
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AskLeaveView(navHostController: NavHostController, vm: LeaveViewModel = hiltViewModel()) {
    val kv = MMKV.defaultMMKV()
    var uname = kv.decodeString("uname", "未登录")!!
    var role=kv.decodeString("role","")!!
    var type by remember {
        mutableStateOf("事假")
    }
    var startTime by remember {
        mutableStateOf(vm.toDate(System.currentTimeMillis()))
    }
    var endTime by remember {
        mutableStateOf(vm.toDate(System.currentTimeMillis()))
    }
    var reason by remember {
        mutableStateOf("")
    }
    var length by remember {
        mutableStateOf(0)
    }

    var isShow by remember {
        mutableStateOf(false)
    }
    var isWho by remember {
        mutableStateOf(0)
    }
    var color by remember {
        mutableStateOf(Color.Black)
    }
    val pickerState = rememberDatePickerState()

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        ToastUtils.showLong("申请成功")
                        navHostController.popBackStack()
                    }

                    else -> {}
                }
            }
        }
    })
    Column(
        Modifier
            .fillMaxSize()
            .padding(20.dp), verticalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        BaseTitle(navHostController = navHostController, title = "请假申请")
        ElevatedCard(colors = CardDefaults.cardColors(containerColor = Color.White)) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(20.dp, 10.dp)
            ) {
                AsyncImage(
                    model = "https://img1.baidu.com/it/u=4035546522,389745751&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1735146000&t=a6cb452f25f5456854d0cc65889449b6",
                    contentDescription = "",
                    modifier = Modifier
                        .size(80.dp)
                        .clip(CircleShape),
                    contentScale = ContentScale.Crop
                )
                Spacer(modifier = Modifier.width(10.dp))
                Column(Modifier.height(80.dp), verticalArrangement = Arrangement.SpaceAround) {
                    Text(text = uname)
                    Text(text = role)
                }

            }
        }
        Row(verticalAlignment = Alignment.CenterVertically) {
            Text(text = "请假类型：")
            RadioButton(selected = type == "事假", onClick = { type = "事假" })
            Text(text = "事假")
            RadioButton(selected = type == "病假", onClick = { type = "病假" })
            Text(text = "病假")
        }

        Row {
            Text(text = "开始时间：")
            OutlinedTextField(value = startTime, onValueChange = {}, readOnly = true,
                trailingIcon = {
                    Icon(imageVector = Icons.Default.DateRange, contentDescription = "",
                        Modifier.clickable {
                            isWho = 1
                            isShow = true
                        })
                })
        }

        Row {
            Text(text = "结束时间：")
            OutlinedTextField(value = endTime, onValueChange = {}, readOnly = true,
                trailingIcon = {
                    Icon(imageVector = Icons.Default.DateRange, contentDescription = "",
                        Modifier.clickable {
                            isWho = 2
                            isShow = true
                        })
                })
        }

        Row {
            Text(text = "请假原因：")
            Box(contentAlignment = Alignment.BottomEnd) {
                OutlinedTextField(
                    value = reason, onValueChange = {
                        Log.i("===", it)
                        if (it.length <= 10) {
                            reason = it
                            length = reason.length
                        }
                    },
                    modifier = Modifier.height(100.dp)
                )
                color = if (length == 10) Color.Red else Color.Black
                Text(
                    text = "$length/10",
                    color = color,
                    modifier = Modifier.offset(x = -6.dp, y = -5.dp)
                )
            }
        }

        Button(onClick = {
            if (reason.isEmpty()) {
                ToastUtils.showLong("原因不能为空")
                return@Button
            }
            vm.sendIntent(
                LeaveIntent.addLeave(Leave(
                    uname = uname,
                    role =role,
                    type=type,
                    startTime = startTime+" 09:00:00",
                    endTime = endTime+" 18:00:00",
                    reason = reason,
                    status = "未审核",
                    createTime = vm.toDateTime(System.currentTimeMillis())
                ))
                /*UserIntent.askLeave(
                    mapOf(
                        "type" to type,
                        "startTime" to startTime+" 09:00:00",
                        "endTime" to endTime+" 18:00:00",
                        "hours" to 8,
                        "reason" to reason
                    )
                )*/
            )
        }, Modifier.fillMaxWidth()) {
            Text(text = "提交")
        }
    }
    if (isShow) {
        DatePickerDialog(onDismissRequest = { isShow = false }, confirmButton = {
            Text(text = "确认", Modifier.clickable {
                if (isWho == 1) {
                    startTime = vm.toDate(pickerState.selectedDateMillis!!)
                } else {
                    endTime = vm.toDate(pickerState.selectedDateMillis!!)
                }
                isShow = false
            })
        }) {
            DatePicker(state = pickerState)
        }
    }
}